//
//  XMSSyncDownloadManager.m
//  
//
//  Created by wjxfhxy on 16/4/26.
//
//

#import "XMSSyncDownloadManager.h"

#import "XMSSimpleDownloadHelper.h"

#import "XMSFileHelper.h"

@interface XMSSyncDownloadManager ()<XMSSimpleDownloadHelperDelegate>
{
    XMSSimpleDownloadHelper *_helper;
}

@property(nonatomic,readonly) NSString *filePath;

@end

@implementation XMSSyncDownloadManager

static NSString*(^s_transferURL)(NSString *URL);

-(void)dealloc
{
    [_helper release_mm];
    superdealloc_mm;
}

+(void)operateNeedTransferURLBlock:(NSString *(^)(NSString *URL))transferURL
{
    if(s_transferURL != NULL)
        Block_release(s_transferURL);
    s_transferURL = NULL;
    if(transferURL != NULL)
        s_transferURL = Block_copy(transferURL);
}

-(NSString*)filePath
{
    return _helper.filePath;
}

-(void)startSyncDownloadURL:(NSString*)URL
{
    NSString *filePath = [[XMSFileHelper tempPath] stringByAppendingPathComponent:[URL lastPathComponent]];
    _helper = [[XMSSimpleDownloadHelper alloc] initWithUrl:URL path:filePath delegate:self];
    
    [CRequestChannelPoolShell addRequestChannel:^CRequestChannel *
    {
        return _helper;
    }];
    
    [_helper startReceiveWaitUntilDone];
    
    _helper.delegate = nil;
    
    [CRequestChannelPoolShell removeRequestChannel:^CRequestChannel *
    {
         return _helper;
    }];
}

- (BOOL)terminateSelfRequest:(BOOL)bRejectrequest
{
    _helper.delegate = nil;
    return [_helper terminateRequest];
}

+(NSString*)startSyncDownloadURL:(NSString*)URL attachDOM:(XMSDataOperationManager*)attachDOM
{
    XMSSyncDownloadManager *manager = [[[XMSSyncDownloadManager alloc] initWithDataOperationManagerDelegate:nil AttachDOM:attachDOM] autorelease_mm];
    
    if(manager == nil)
        return nil;
    
    [manager startSyncDownloadURL:URL];
    
    [attachDOM detachDataOperationManager:@[manager]];
    
    NSString *filePath = manager.filePath;
    if([XMSFileHelper isFileExist:filePath])
        return filePath;
    return @"";
}

- (void)simpleDownloadHelperWillStartConnect:(XMSSimpleDownloadHelper*)helper
{
    
}

- (void)simpleDownloadHelperDidStartConnect:(XMSSimpleDownloadHelper*)helper
{
    
}

- (void)simpleDownloadHelperFinishLoading:(XMSSimpleDownloadHelper*)helper
{
    
}

- (void)simpleDownloadHelper:(XMSSimpleDownloadHelper*)helper error:(NSError*)error
{
    
}

- (NSString*)simpleDownloadHelper:(XMSSimpleDownloadHelper *)helper needTransferURL:(NSString *)URL
{
    if(s_transferURL != NULL)
        return s_transferURL(URL);
    
    return URL;
}

@end
